using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebUpdaterAdminCore.Data;
using WebUpdaterAdminCore.Models;

namespace WebUpdaterAdminCore.WebApi
{
    [Produces("application/json")]
    [Route("api/ClientStatus")]
    public class ClientStatusController : Controller
    {
        private ApplicationDbContext _dbContext;
        private UpdaterSocketServerService _socketServerService;

        public ClientStatusController(ApplicationDbContext dbContext,
            UpdaterSocketServerService updaterSocket)
        {
            _dbContext = dbContext;
            _socketServerService = updaterSocket;
        }
        // GET: api/ClientStatus
        [HttpGet]
        public IActionResult Get(int pageNo = 1,int pageSize=-1)
        {
            var data = GetAllClientStatus();
            //页码是从1开始,但分页索引以0开始
            pageNo = pageNo - 1 > 0 ? pageNo - 1 : 0;
            int skipCount = pageNo * pageSize;
            var query = data.Skip(skipCount);
            if (pageSize > 0)
            {
                query = query.Take(pageSize);
            }
            var pageData = new GetClientStatusViewModel
            {
                Total = data.Count,
                PageNo = pageNo,
                PageSize = pageSize,
                PageData = query
            };
            var result = new OKResult<GetClientStatusViewModel> {
                Data = pageData
            };
            return Json(result);
        }

        // GET: api/ClientStatus/5
        [HttpGet("{id}", Name = "Get")]
        public IActionResult Get(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return Json(new ErrorResult(100101, "参数不能为空"));
            }
            var data = GetAllClientStatus().Where(w => w.ClientId == id).FirstOrDefault();
            return Json(new OKResult<SocketSessionModel>(data));
        }
        
        // POST: api/ClientStatus
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }
        
        /// <summary>
        /// 修改客户端信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="clientStatusModel"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<IActionResult> Put(string id, [FromBody] ClientStatusModifyViewModel model)
        {

            var clientInfo = await _dbContext.ClientInfos.FindAsync(id);
          
            if(clientInfo == null)
            {
                return Json(new ErrorResult(100102, "客户端不存在"));
            }
            var clientGroup = await _dbContext.ClientGroups.FindAsync(model.GroupId);
            if(clientGroup == null)
            {
                return Json(new ErrorResult(100102, "分组不存在"));
            }
            clientInfo.ClientName = string.IsNullOrEmpty(model.ClientName) ? clientInfo.ClientId : model.ClientName;
            clientInfo.Remarks = model.Remarks;
            clientInfo.Group = clientGroup;
            _dbContext.ClientInfos.Update(clientInfo);

            await _dbContext.SaveChangesAsync();
            
            return Json(new OKResult<ClientGroup>(clientGroup));
        }
        

        private List<SocketSessionModel> GetAllClientStatus()
        {
            List<SocketSessionModel> socketSessionModels = new List<SocketSessionModel>();
            if (_socketServerService != null)
            {
                var clientStatus = _dbContext.ClientInfos
                    .Include(ci=>ci.ClientStatus)
                    .Include(ci=>ci.Group);
                var allSession = _socketServerService.GetAllSessions();

                foreach(var cs in clientStatus)
                {
                    var ssId = cs.ClientStatus.SessionId;
                    var session = _socketServerService.GetSessionByID(ssId);
                    bool connected = true;
                    string remoteIp = "";
                    DateTime activeTime = DateTime.MinValue, startTime = DateTime.MinValue;
                    if (session == null)
                    {
                        connected = false;
                    }
                    else
                    {
                        connected = true;
                        connected = session.Connected;
                        remoteIp = session.RemoteEndPoint.Address.ToString();
                        activeTime = session.LastActiveTime;
                        startTime = session.StartTime;
                    }
                    var model = new SocketSessionModel
                    {
                        ClientId = cs.ClientId,
                        ClientName = cs.ClientName,
                        GroupName = cs.Group.Name,
                        RemoteIP = remoteIp,//cs.ClientStatus.ClientIP,
                        Connected = connected,//cs.ClientStatus.Connected,
                        SessionId = ssId,
                        LastActiveTime = activeTime,//cs.ClientStatus.LastActiveTime,
                        StartTime = startTime,//cs.ClientStatus.StartTime,
                        Remarks = cs.Remarks
                    };
                    socketSessionModels.Add(model);
                }
            }
            return socketSessionModels;

        }
    }
}
